惯例先贴代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>

<!--<item name="android:actionMenuTextColor">@android:color/white</item>-->
<!--<item name="actionOverflowMenuStyle">@style/PopupMenu</item>-->
</style>

<style name="toolbar_style" parent="ThemeOverlay.AppCompat.Dark.ActionBar" >
<item name="android:homeAsUpIndicator">@android:drawable/ic_menu_help</item>
<item name="android:actionMenuTextColor">#11eeff</item>
<item name="android:actionOverflowButtonStyle">@style/OverflowButtonStyle</item>
</style>

<style name="OverflowButtonStyle" parent="@android:style/Widget.ActionButton.Overflow">
<item name="android:src">@android:drawable/ic_lock_idle_low_battery</item>
</style>
<!--设置popupwindow样式-->
<style name="PopupMenu" parent="@style/Widget.AppCompat.Light.PopupMenu.Overflow" >
<item name="android:colorBackground">@color/colorPrimary</item>
<item name="android:textColor">@android:color/white</item>
<!--弹出菜单与标题栏的间距-->
<item name="android:dropDownVerticalOffset">1dip</item>
<item name="overlapAnchor">false</item>
</style>
</resources>

在xml里给appbarLayout设置上android:theme="@style/toolbar_style"

  1. 自定义title并居中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <android.support.design.widget.AppBarLayout
    android:theme="@style/toolbar_style"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    app:popupTheme="@style/PopupMenu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
    android:text="title"
    android:layout_gravity="center"
    android:textColor="#fff"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
    </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    让toolbar不显示title,supportActionBar.setDisplayShowTitleEnabled(false)

    1
    2
    3
    4
    5
    setSupportActionBar(toolbar)
    with(supportActionBar!!) {
    setDisplayHomeAsUpEnabled(true)
    setDisplayShowTitleEnabled(false)
    }
  2. 设置R.id.home,也就是toolbar左边那个返回按钮的图标样式
    supportActionBar.setDisplayHomeAsUpEnabled(true)先让图标显示出来
    <item name="android:homeAsUpIndicator">@android:drawable/ic_menu_help</item>

  3. 上面代码中ThemeOverlay.AppCompat.Dark.ActionBar可以让按钮变白色

  4. R.style.PopupMenu里的设置是控制多出来的的optionMenu弹出pop的样式,需要在xml中给toolbar设置上这个主题

  5. 设置optionMenu的字体颜色<item name="android:actionMenuTextColor">#11eeff</item>

6.设置右边那三个点的图标样式<item name="android:actionOverflowButtonStyle">@style/OverflowButtonStyle</item>